//
//  WLUpLoadCenter.m
//  WanLian
//
//  Created by 123456 on 2018/12/7.
//  Copyright © 2018 wanlian. All rights reserved.
//

#import "WLUpLoadCenter.h"
#import "WLFileUpDownLoadModel.h"
#import "WLHttpManager.h"
#import "WLUploadManager.h"
#import "WLDataBaseManager.h"
#import "MonitorFlow.h"
#import "WLFileHandle.h"
#import "WLFileSocketManager.h"
#import "WLSocketManager.h"
#import "WLFileRequest.h"

@interface WLUpLoadCenter ()

@end

@implementation WLUpLoadCenter
impl_single_instance(WLUpLoadCenter)
- (void)configure {
    
    NSArray *localTasks = [[WLDataBaseManager shareInstance] queryTotalListWithTableName:[WLFileUpDownLoadModel getTableNameWithModelType:WLDataBaseModelTypeUpload] className:[WLFileUpDownLoadModel class]];
    for (WLFileUpDownLoadModel *model in localTasks) {
        if (model.loadState == FileLoadingStateRunning) {
            model.loadState = FileLoadingStateWaiting;
        }
    }
    if (localTasks.count > 0) {
        [self.totalTaskArray addObjectsFromArray:localTasks];
    }
    self.currentTaskIndex = -1;
}

#pragma 上传视频
/**
- (NSURLSessionDataTask *)uploadTaskWithModel:(WLFileUpDownLoadModel *)model
                    progress:(void (^)(float))uploadProgress
                     success:(void (^)(NSDictionary *successDict))success
                     failure:(void (^)(NSString *errorMsg, NSInteger errorTag))failure
                       error:(void (^)(NSError *error))err {
    NSURLSessionDataTask *dataTask = nil;
    
    
    if (model.fileType == SPFileTypeVideo) {
       dataTask = [WLHttpManager WLBackgroundUploadPost:@"/cgi-bin/luci/file/upload/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            [formData appendPartWithFileURL:model.fileURL name:@"video" fileName:model.filePath.lastPathComponent mimeType:@"video/mp4" error:nil];
       } progress:^(NSProgress *progress) {
           if (uploadProgress) {
               uploadProgress(progress.fractionCompleted);
           }
       } success:success failure:failure error:err inView:nil];
    } else if (model.fileType == SPFileTypePhoto) {
        dataTask = [WLHttpManager WLBackgroundUploadPost:@"/cgi-bin/luci/file/upload/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            if (model.fileData.length > 0) {
                [formData appendPartWithFileData:model.fileData name:@"photo" fileName:model.fileName mimeType:@"image/jpeg"];
            }
        } progress:^(NSProgress *progress) {
            if (uploadProgress) {
                uploadProgress(progress.fractionCompleted);
            }
        }  success:success failure:failure error:err inView:nil];
    }
    return dataTask;

}*/
- (WLSocketWorker *)uploadTaskWithModel:(WLFileUpDownLoadModel *)model
                                     progress:(void (^)(float))uploadProgress
                                      success:(void (^)(NSDictionary *successDict))success
                                      failure:(void (^)(NSString *errorMsg, NSInteger errorTag))failure
                                        error:(void (^)(NSError *error))err {
    WLFileSocketManager *socketManager = [WLFileSocketManager shareInstance];
    WLFileRequest *request = [model getRequestModel];
    request.host = [WLCommonTool getFileUpDownloadHost];
    request.port = 9002;
    WLSocketWorker *dataTask = [socketManager uploadTaskWithModel:request progress:uploadProgress success:success failure:failure error:err];
    return dataTask;
    
}
//
//- (NSURLSessionDataTask *)uploadTaskWithModel:(WLFileUpDownLoadModel *)model
//                                      progress:(void (^)(float uploadProgress))uploadProgress
//                                       success:(void (^)(NSDictionary *successDict))success
//                                       failure:(void (^)(NSString *errorMsg, NSInteger errorTag))failure
//                                         error:(void (^)(NSError *error))err {
//    NSURLSessionDataTask *dataTask = nil;
//    if (model.fileType == SPFileTypeVideo) {
//       dataTask = [[WLUploadManager shareInstance] uploadUrl:model.fileURL withModel:model completion:nil];
//    } else if (model.fileType == SPFileTypePhoto) {
//        dataTask = [WLHttpManager WLBackgroundUploadPost:@"/cgi-bin/luci/file/upload/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//            [formData appendPartWithFileData:model.fileData name:@"photo" fileName:model.fileName mimeType:@"image/jpeg"];
//        } progress:^(NSProgress *uploadProg) {
//            if (uploadProgress) {
//                uploadProgress(uploadProg.fractionCompleted);
//            }
//        } success:success failure:failure error:err inView:nil];
//    }
//    return dataTask;
//
//}

- (WLSocketWorker *)startTaskWithModel:(WLFileUpDownLoadModel *)model
{
    
//    if (!model.fileURL) {//先移动到本地路径
//        NSURL *newVideoUrl ; //一般.mp4
//        NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
//        newVideoUrl = [NSURL fileURLWithPath:[documentPath stringByAppendingFormat:@"/%@",  model.fileName]];//这个是保存在app自己的沙盒路径里，后面可以选择是否在上传后删除掉。我建议删除掉，免得占空间。
//
//        NSError *err = nil;
//        BOOL suc = [WLFileHandle copyItemAtPath:model.mediaLocalURL.path toPath:newVideoUrl.path overwrite:YES error:&err];
//        if (suc) {
//            model.fileURL = newVideoUrl;
//            model.filePath = newVideoUrl.path;
//        } else {
//            WLLog(@"转移文件失败");
//            return nil;
//        }
//    }
    
    [self startMonitor];
    model.loadState = FileLoadingStateRunning;
    self.currentTaskIndex = (NSInteger)[self.totalTaskArray indexOfObject:model];
//    dispatch_async(dispatch_get_main_queue(), ^{
    if (self.delegate && [self.delegate respondsToSelector:@selector(didStartTastWithIndex:)]) {//通知外部开始新的任务了
        [self.delegate didStartTastWithIndex:[self.totalTaskArray indexOfObject:model]];
    }
//    });
    
    WLWkSelf
    WLSocketWorker *dataTask = [self uploadTaskWithModel:model progress:^(float uploadProgress) {
//            [weakSelf.speedMonitor startMonitor];
        [weakSelf dealWithProcess:uploadProgress model:model];
    } success:^(NSDictionary *successDict) {
        [weakSelf dealWithSuccess:successDict model:model];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf dealWithFailure:errorMsg errorTag:errorTag model:model];
    } error:^(NSError *error) {
        [weakSelf dealWithFailure:@"" errorTag:0 model:model];
    }];
    model.dataTask = dataTask;
    return dataTask;
}

//- (void)removeLocalFile:(WLFileUpDownLoadModel *)model {
//    
//    [WLFileHandle removeItemAtPath:model.filePath error:nil];
//}

@end
